<template>
  <div>
    <!-- table -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="data"
        :pagination="false"
        :loading="memberLoading"
      >
        <template v-for="(col, i) in ['name', 'money', 'task_cnt', 'back_color', 'front_color']" :slot="col" slot-scope="text, record">
          <a-input
            :key="col"
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            :placeholder="columns[i].title"
            @change="e => handleChange(e.target.value, record.id, col)"
          />
          <template v-else>{{ text }}</template>
        </template>
        <template slot="operation" slot-scope="text, record">
          <template v-if="record.editable">
            <span v-if="record.isNew">
              <a @click="saveRow(record)">{{ $t('noticeCard.tj') }}</a>
              <a-divider type="vertical" />
              <a-popconfirm title="$t('noticeCard.sfysccx')" @confirm="remove(record.id)">
                <a>{{ $t('noticeCard.sc') }}</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="saveRow(record)">{{ $t('noticeCard.bc') }}</a>
              <a-divider type="vertical" />
              <a @click="cancel(record.id)">{{ $t('noticeCard.qx') }}</a>
            </span>
          </template>
          <span v-else>
            <a @click="toggle(record.id)">{{ $t('noticeCard.bj') }}</a>
            <a-divider type="vertical" />
            <a-popconfirm title="$t('noticeCard.sfysccx')" @confirm="remove(record.id)">
              <a>{{ $t('noticeCard.sc') }}</a>
            </a-popconfirm>
          </span>
        </template>
      </a-table>
      <a-button style="width: 100%; margin-top: 16px; margin-bottom: 8px" type="dashed" icon="plus" @click="newMember">{{ $t('noticeCard.xzjl') }}</a-button>
    </a-card>

    <!-- fixed footer toolbar -->
    <footer-tool-bar :style="{ width: isSideMenu() && isDesktop() ? `calc(100% - ${sidebarOpened ? 256 : 80}px)` : '100%'}">
      <span class="popover-wrapper">
        <a-popover title="$t('noticeCard.bdxyxx')" overlayClassName="antd-pro-pages-forms-style-errorPopover" trigger="click" :getPopupContainer="trigger => trigger.parentNode">
          <template slot="content">
            <li v-for="item in errors" :key="item.key" @click="scrollToField(item.key)" class="antd-pro-pages-forms-style-errorListItem">
              <a-icon type="cross-circle-o" class="antd-pro-pages-forms-style-errorIcon" />
              <div class="">{{ item.message }}</div>
              <div class="antd-pro-pages-forms-style-errorField">{{ item.fieldLabel }}</div>
            </li>
          </template>
          <span class="antd-pro-pages-forms-style-errorIcon" v-if="errors.length > 0">
            <a-icon type="exclamation-circle" />{{ errors.length }}
          </span>
        </a-popover>
      </span>
      <a-button type="primary" @click="validate" :loading="loading">{{ $t('noticeCard.tj') }}</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
import RepositoryForm from '../../user/RepositoryForm'
import TaskForm from '../../user/TaskForm'
import FooterToolBar from '@/components/FooterToolbar'
import CreateForm from './CreateForm'
import { mixin, mixinDevice } from '@/utils/mixin'

const fieldLabels = {
  name: this.$t('noticeCard.ckm'),
  url: this.$t('noticeCard.ckym'),
  owner: this.$t('noticeCard.ckgly'),
  approver: this.$t('noticeCard.spr'),
  dateRange: this.$t('noticeCard.sxrq'),
  type: this.$t('noticeCard.cklx'),
  name2: this.$t('noticeCard.rwm'),
  url2: this.$t('noticeCard.rwms'),
  owner2: this.$t('noticeCard.zxr'),
  approver2: this.$t('noticeCard.zrr'),
  dateRange2: this.$t('noticeCard.sxrq'),
  type2: this.$t('noticeCard.rwlx')
}

export default {
  name: 'AdvancedForm',
  mixins: [mixin, mixinDevice],
  components: {
    FooterToolBar,
    RepositoryForm,
    TaskForm,
    CreateForm
  },
  data () {
    return {
      description: this.$t('noticeCard.gjbdcjyycxsrhtjdplsjdcj'),
      loading: false,
      memberLoading: false,
      curr_id: '',
      // table
      columns: [
        {
          title: this.$t('noticeCard.mc'),
          dataIndex: 'name',
          key: 'name',
          width: '20%',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: this.$t('noticeCard.czje'),
          dataIndex: 'money',
          key: 'money',
          width: '20%',
          scopedSlots: { customRender: 'money' }
        },
        {
          title: this.$t('noticeCard.rwcs'),
          dataIndex: 'task_cnt',
          key: 'task_cnt',
          width: '10%',
          scopedSlots: { customRender: 'task_cnt' }
        },
        {
          title: this.$t('noticeCard.bjs'),
          dataIndex: 'back_color',
          key: 'back_color',
          width: '15%',
          scopedSlots: { customRender: 'back_color' }
        },
        {
          title: this.$t('noticeCard.qjs'),
          dataIndex: 'front_color',
          key: 'front_color',
          width: '15%',
          scopedSlots: { customRender: 'front_color' }
        },
        {
          title: this.$t('noticeCard.hyrs'),
          dataIndex: 'member_cnt',
          key: 'member_cnt',
          width: '10%',
          scopedSlots: { customRender: 'member_cnt' }
        },
        {
          title: this.$t('noticeCard.cz'),
          key: 'action',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      data: [],

      errors: []
    }
  },
  created () {
    this.getList()
  },
  methods: {
    handleOk (val) {
      this.$http.post('/member/recharge', this.$qs.stringify({
        id: this.curr_id,
        money: val.desc
      })).then(res => {
        if (res.code === 0) {
          this.getList()
          this.$notification.success({
            message: this.$t('noticeCard.cg'),
            description: res.msg
          })
        } else {
          this.$notification.error({
            message: this.$t('noticeCard.sb'),
            description: res.msg
          })
        }
      }).catch(err => {
        this.$notification.error({
          message: this.$t('noticeCard.sb'),
          description: err.message
        })
      })
    },
    getList () {
      this.$http.get('/member/card_list').then(res => {
        this.data = res
      }).catch(err => {
        this.$notification.error({
          message: this.$t('noticeCard.sb'),
          description: err.message
        })
      })
    },
    handleClickRecharge (id) {
      this.curr_id = id
      this.$refs.createModal.add()
    },
    handleSubmit (e) {
      e.preventDefault()
    },
    handleClickActive (id) {
      // 2
    },
    handleClickUnActive (id) {
      // 3
    },
    newMember () {
      const length = this.data.length
      this.data.push({
        key: length === 0 ? '1' : (parseInt(this.data[length - 1].key) + 1).toString(),
        name: '',
        workId: '',
        department: '',
        editable: true,
        isNew: true
      })
    },
    remove (id) {
      this.$http.post('/member/card/delete', this.$qs.stringify({
        id: id
      })).then(res => {
        const newData = this.data.filter(item => item.id !== id)
        this.data = newData
      }).catch(err => {
        this.$notification.error({
          message: this.$t('noticeCard.sb'),
          description: err.message
        })
      })
    },
    saveRow (record) {
      this.memberLoading = true
      const { money, name, task_cnt, back_color, front_color, id } = record
      if (!name || !money || !task_cnt || !back_color || !front_color) {
        this.memberLoading = false
        this.$message.error(this.$t('noticeCard.qtxwzcyxx'))
        return
      }
      this.$http.post('/member/save_card', this.$qs.stringify({
        name: name,
        money: money,
        task_cnt: task_cnt,
        back_color: back_color,
        front_color: front_color,
        id: id
      })).then(res => {
        if (res.code === 0) {
          this.getList()
          this.$notification.success({
            message: this.$t('noticeCard.cg'),
            description: res.msg
          })
        } else {
          this.$notification.error({
            message: this.$t('noticeCard.sb'),
            description: res.msg
          })
        }
      }).catch(err => {
        this.$notification.error({
          message: this.$t('noticeCard.sb'),
          description: err.message
        })
      }).then(() => {
        this.memberLoading = false
      })
    },
    toggle (id) {
      let index = -1
      let target = ''
      for (let i = 0; i < this.data.length; i++) {
        if (this.data[i].id === id) {
          index = i
          target = this.data[i]
          break
        }
      }
      target._originalData = { ...target }
      target.editable = !target.editable
      this.$set(this.data, index, target)
    },
    getRowByKey (key, newData) {
      const data = this.data
      return (newData || data).find(item => item.key === key)
    },
    cancel (id) {
      const target = this.data.find(item => item.id === id)
      Object.keys(target).forEach(id => { target[id] = target._originalData[id] })
      target._originalData = undefined
    },
    handleChange (value, id, column) {
      const newData = [...this.data]
      const target = newData.find(item => id === item.id)
      if (target) {
        target[column] = value
        this.data = newData
      }
    },

    // 最终全页面提交
    validate () {
      const { $refs: { repository, task }, $notification } = this
      const repositoryForm = new Promise((resolve, reject) => {
        repository.form.validateFields((err, values) => {
          if (err) {
            reject(err)
            return
          }
          resolve(values)
        })
      })
      const taskForm = new Promise((resolve, reject) => {
        task.form.validateFields((err, values) => {
          if (err) {
            reject(err)
            return
          }
          resolve(values)
        })
      })

      // clean this.errors
      this.errors = []
      Promise.all([repositoryForm, taskForm]).then(values => {
        $notification['error']({
          message: 'Received values of form:',
          description: JSON.stringify(values)
        })
      }).catch(() => {
        const errors = Object.assign({}, repository.form.getFieldsError(), task.form.getFieldsError())
        const tmp = { ...errors }
        this.errorList(tmp)
      })
    },
    errorList (errors) {
      if (!errors || errors.length === 0) {
        return
      }
      this.errors = Object.keys(errors)
        .filter(key => errors[key])
        .map(key => ({
          key: key,
          message: errors[key][0],
          fieldLabel: fieldLabels[key]
        }))
    },
    scrollToField (fieldKey) {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`)
      if (labelNode) {
        labelNode.scrollIntoView(true)
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .card{
    margin-bottom: 24px;
  }
  .popover-wrapper {
    /deep/ .antd-pro-pages-forms-style-errorPopover .ant-popover-inner-content {
      min-width: 256px;
      max-height: 290px;
      padding: 0;
      overflow: auto;
    }
  }
  .antd-pro-pages-forms-style-errorIcon {
    user-select: none;
    margin-right: 24px;
    color: #f5222d;
    cursor: pointer;
    i {
          margin-right: 4px;
    }
  }
  .antd-pro-pages-forms-style-errorListItem {
    padding: 8px 16px;
    list-style: none;
    border-bottom: 1px solid #e8e8e8;
    cursor: pointer;
    transition: all .3s;

    &:hover {
      background: #e6f7ff;
    }
    .antd-pro-pages-forms-style-errorIcon {
      float: left;
      margin-top: 4px;
      margin-right: 12px;
      padding-bottom: 22px;
      color: #f5222d;
    }
    .antd-pro-pages-forms-style-errorField {
      margin-top: 2px;
      color: rgba(0,0,0,.45);
      font-size: 12px;
    }
  }
</style>
